package ru.passivemoney.root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.passivemoney.common.Credentials;
import ru.passivemoney.common.Utils;
import ru.passivemoney.common.UtilsOrders;
import ru.passivemoney.manage.orders.OrdersHolder;

import com.dukascopy.api.IOrder;
import com.dukascopy.api.JFException;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ISystemListener;

public class Listener implements ISystemListener {
	private static final Logger logger = LoggerFactory.getLogger(Listener.class);
	
	private IClient client;
	private Credentials credentials;

	public Listener(){}
	
	public Listener(IClient client, Credentials credentials){
		this.client = client;
	}
	
	@Override
	public void onStart(long processId) {
		logger.info("Strategy started: " + processId);
	}

	@Override
	public void onStop(long processId) {
		logger.info("Strategy stopped: " + processId);
	}

	@Override
	public void onConnect() {
		logger.info("Connected!");
	}

	@Override
	public void onDisconnect() {
		logger.warn("Disconnected!");
		Utils.connectClientInfinity(client, credentials);
		OrdersHolder.clearOpenedOrders();
		OrdersHolder.clearCreatedOrders();
		boolean exceptionOccured;
		do{
			try {
				for(IOrder order : EngineHolder.getEngine().getOrders()){
					if(UtilsOrders.isOrderOpenedOrFilled(order)){
						OrdersHolder.putToOpenedOrders(order.getInstrument(), order);
					}else{
						OrdersHolder.putToCreatedOrders(order.getInstrument(), order);
					}
				}
				exceptionOccured = false;
			} catch (JFException e) {
				logger.error("", e);
				exceptionOccured = true;
				try {
					Thread.sleep(5000L);
				} catch (InterruptedException e1) {
					logger.error("", e);
				}
			}
		}while(exceptionOccured);
	}

	public IClient getClient() {
		return client;
	}

	public Credentials getCredentials() {
		return credentials;
	}
	
	
}
